<template>
  <div class="user-center">
    <page-header title="个人中心" subtitle="管理您的个人信息和就医记录"></page-header>
    
    <el-row :gutter="20">
      <el-col :span="6">
        <el-card class="user-info-card">
          <div class="user-avatar">
            <el-avatar :size="100" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
            <div class="upload-avatar">
              <el-button type="primary" size="small" plain>更换头像</el-button>
            </div>
          </div>
          
          <div class="user-basic-info">
            <h3>{{ userInfo.name }}</h3>
            <p class="user-id">ID: {{ userInfo.id }}</p>
          </div>
          
          <el-divider></el-divider>
          
          <el-menu
            :default-active="activeMenu"
            class="user-menu"
            @select="handleMenuSelect"
          >
            <el-menu-item index="profile">
              <el-icon><User /></el-icon>
              <span>个人资料</span>
            </el-menu-item>
            <el-menu-item index="medical-records">
              <el-icon><Document /></el-icon>
              <span>就医记录</span>
            </el-menu-item>
            <el-menu-item index="appointments">
              <el-icon><Calendar /></el-icon>
              <span>我的预约</span>
            </el-menu-item>
            <el-menu-item index="family">
              <el-icon><UserFilled /></el-icon>
              <span>家庭成员</span>
            </el-menu-item>
            <el-menu-item index="settings">
              <el-icon><Setting /></el-icon>
              <span>账号设置</span>
            </el-menu-item>
          </el-menu>
        </el-card>
      </el-col>
      
      <el-col :span="18">
        <!-- 个人资料 -->
        <el-card v-if="activeMenu === 'profile'" class="content-card">
          <template #header>
            <div class="card-header">
              <span>个人资料</span>
              <el-button type="primary" size="small" @click="editProfile">编辑资料</el-button>
            </div>
          </template>
          
          <el-form :model="userInfo" label-width="100px" :disabled="!isEditing">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="姓名">
                  <el-input v-model="userInfo.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别">
                  <el-select v-model="userInfo.gender" style="width: 100%;">
                    <el-option label="男" value="male"></el-option>
                    <el-option label="女" value="female"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="出生日期">
                  <el-date-picker v-model="userInfo.birthday" type="date" style="width: 100%;"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="身份证号">
                  <el-input v-model="userInfo.idCard"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="手机号码">
                  <el-input v-model="userInfo.phone"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="邮箱">
                  <el-input v-model="userInfo.email"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            
            <el-form-item label="地址">
              <el-input v-model="userInfo.address"></el-input>
            </el-form-item>
            
            <el-form-item label="医疗保险">
              <el-input v-model="userInfo.insurance"></el-input>
            </el-form-item>
            
            <el-form-item label="过敏史">
              <el-input v-model="userInfo.allergies" type="textarea" :rows="2"></el-input>
            </el-form-item>
            
            <el-form-item v-if="isEditing">
              <el-button type="primary" @click="saveProfile">保存</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
        
        <!-- 就医记录 -->
        <el-card v-if="activeMenu === 'medical-records'" class="content-card">
          <template #header>
            <div class="card-header">
              <span>就医记录</span>
              <el-input
                v-model="searchMedicalRecord"
                placeholder="搜索就医记录"
                prefix-icon="Search"
                clearable
                style="width: 200px"
              ></el-input>
            </div>
          </template>
          
          <el-table :data="medicalRecords" style="width: 100%" v-if="medicalRecords.length > 0">
            <el-table-column prop="date" label="就诊日期" sortable width="180"></el-table-column>
            <el-table-column prop="department" label="科室"></el-table-column>
            <el-table-column prop="doctor" label="医生"></el-table-column>
            <el-table-column prop="diagnosis" label="诊断"></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="viewMedicalRecord(scope.row)">查看详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <empty-state v-else description="暂无就医记录"></empty-state>
        </el-card>
        
        <!-- 我的预约 -->
        <el-card v-if="activeMenu === 'appointments'" class="content-card">
          <template #header>
            <div class="card-header">
              <span>我的预约</span>
              <div>
                <el-radio-group v-model="appointmentType" size="small">
                  <el-radio-button label="all">全部</el-radio-button>
                  <el-radio-button label="upcoming">即将到来</el-radio-button>
                  <el-radio-button label="past">历史预约</el-radio-button>
                </el-radio-group>
              </div>
            </div>
          </template>
          
          <el-table :data="filteredAppointments" style="width: 100%" v-if="filteredAppointments.length > 0">
            <el-table-column prop="date" label="预约日期" sortable width="180"></el-table-column>
            <el-table-column prop="time" label="预约时间" width="100"></el-table-column>
            <el-table-column prop="department" label="科室"></el-table-column>
            <el-table-column prop="doctor" label="医生"></el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <status-tag :status="scope.row.status"></status-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button 
                  v-if="scope.row.status === '未开始'" 
                  size="small" 
                  type="danger" 
                  @click="cancelAppointment(scope.row)"
                >取消预约</el-button>
                <el-button 
                  v-if="scope.row.status === '已完成'" 
                  size="small" 
                  type="primary" 
                  @click="evaluateAppointment(scope.row)"
                >评价</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <empty-state v-else description="暂无预约记录" button-text="立即预约" @action="goToAppointment"></empty-state>
        </el-card>
        
        <!-- 家庭成员 -->
        <el-card v-if="activeMenu === 'family'" class="content-card">
          <template #header>
            <div class="card-header">
              <span>家庭成员</span>
              <el-button type="primary" size="small" @click="addFamilyMember">添加成员</el-button>
            </div>
          </template>
          
          <el-table :data="familyMembers" style="width: 100%" v-if="familyMembers.length > 0">
            <el-table-column prop="name" label="姓名"></el-table-column>
            <el-table-column prop="relation" label="关系"></el-table-column>
            <el-table-column prop="gender" label="性别" width="80">
              <template #default="scope">
                {{ scope.row.gender === 'male' ? '男' : '女' }}
              </template>
            </el-table-column>
            <el-table-column prop="birthday" label="出生日期" width="120"></el-table-column>
            <el-table-column prop="idCard" label="身份证号" width="180"></el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="scope">
                <el-button size="small" @click="editFamilyMember(scope.row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteFamilyMember(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <empty-state v-else description="暂无家庭成员" button-text="添加成员" @action="addFamilyMember"></empty-state>
        </el-card>
        
        <!-- 账号设置 -->
        <el-card v-if="activeMenu === 'settings'" class="content-card">
          <template #header>
            <div class="card-header">
              <span>账号设置</span>
            </div>
          </template>
          
          <el-tabs>
            <el-tab-pane label="修改密码">
              <el-form :model="passwordForm" label-width="100px">
                <el-form-item label="当前密码">
                  <el-input v-model="passwordForm.oldPassword" type="password" show-password></el-input>
                </el-form-item>
                <el-form-item label="新密码">
                  <el-input v-model="passwordForm.newPassword" type="password" show-password></el-input>
                </el-form-item>
                <el-form-item label="确认密码">
                  <el-input v-model="passwordForm.confirmPassword" type="password" show-password></el-input>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="changePassword">修改密码</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
            
            <el-tab-pane label="隐私设置">
              <el-form :model="privacySettings" label-width="200px">
                <el-form-item label="允许系统发送短信通知">
                  <el-switch v-model="privacySettings.allowSms"></el-switch>
                </el-form-item>
                <el-form-item label="允许系统发送邮件通知">
                  <el-switch v-model="privacySettings.allowEmail"></el-switch>
                </el-form-item>
                <el-form-item label="允许共享我的就医记录">
                  <el-switch v-model="privacySettings.shareMedicalRecords"></el-switch>
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="savePrivacySettings">保存设置</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 查看就医记录详情对话框 -->
    <el-dialog v-model="medicalRecordDialogVisible" title="就医记录详情" width="60%">
      <div v-if="selectedMedicalRecord" class="record-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="就诊日期">{{ selectedMedicalRecord.date }}</el-descriptions-item>
          <el-descriptions-item label="就诊科室">{{ selectedMedicalRecord.department }}</el-descriptions-item>
          <el-descriptions-item label="主治医生">{{ selectedMedicalRecord.doctor }}</el-descriptions-item>
          <el-descriptions-item label="病历号">{{ selectedMedicalRecord.recordNo }}</el-descriptions-item>
          <el-descriptions-item label="主诉" :span="2">{{ selectedMedicalRecord.complaint }}</el-descriptions-item>
          <el-descriptions-item label="诊断结果" :span="2">{{ selectedMedicalRecord.diagnosis }}</el-descriptions-item>
          <el-descriptions-item label="处方" :span="2">{{ selectedMedicalRecord.prescription }}</el-descriptions-item>
          <el-descriptions-item label="医嘱" :span="2">{{ selectedMedicalRecord.advice }}</el-descriptions-item>
        </el-descriptions>
        
        <div class="record-actions">
          <el-button type="primary" @click="printMedicalRecord">打印</el-button>
          <el-button @click="downloadMedicalRecord">下载</el-button>
        </div>
      </div>
    </el-dialog>
    
    <!-- 家庭成员编辑对话框 -->
    <el-dialog 
      v-model="familyMemberDialogVisible" 
      :title="familyMemberDialogType === 'add' ? '添加家庭成员' : '编辑家庭成员'" 
      width="50%"
    >
      <el-form :model="familyMemberForm" label-width="100px">
        <el-form-item label="姓名">
          <el-input v-model="familyMemberForm.name"></el-input>
        </el-form-item>
        <el-form-item label="关系">
          <el-select v-model="familyMemberForm.relation" style="width: 100%;">
            <el-option label="父亲" value="father"></el-option>
            <el-option label="母亲" value="mother"></el-option>
            <el-option label="配偶" value="spouse"></el-option>
            <el-option label="子女" value="child"></el-option>
            <el-option label="其他" value="other"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="familyMemberForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="出生日期">
          <el-date-picker v-model="familyMemberForm.birthday" type="date" style="width: 100%;"></el-date-picker>
        </el-form-item>
        <el-form-item label="身份证号">
          <el-input v-model="familyMemberForm.idCard"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="familyMemberDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveFamilyMember">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import PageHeader from '@/components/PageHeader.vue'
import EmptyState from '@/components/EmptyState.vue'
import StatusTag from '@/components/StatusTag.vue'
import { 
  User, 
  Document, 
  Calendar, 
  UserFilled, 
  Setting, 
  Search 
} from '@element-plus/icons-vue'

const router = useRouter()
const activeMenu = ref('profile')
const isEditing = ref(false)
const searchMedicalRecord = ref('')
const appointmentType = ref('all')
const medicalRecordDialogVisible = ref(false)
const selectedMedicalRecord = ref(null)
const familyMemberDialogVisible = ref(false)
const familyMemberDialogType = ref('add')

// 用户信息
const userInfo = reactive({
  id: 'U12345678',
  name: '张三',
  gender: 'male',
  birthday: '1990-01-01',
  idCard: '110101199001011234',
  phone: '13800138000',
  email: 'zhangsan@example.com',
  address: '北京市海淀区XX路XX号',
  insurance: '城镇职工医疗保险',
  allergies: '青霉素过敏'
})

// 就医记录
const medicalRecords = reactive([
  {
    id: 1,
    date: '2023-04-15',
    department: '内科',
    doctor: '李医生',
    diagnosis: '上呼吸道感染',
    recordNo: 'MR20230415001',
    complaint: '发热、咳嗽3天',
    prescription: '感冒灵颗粒 10g 每日3次\n布洛芬缓释胶囊 0.3g 每日2次',
    advice: '多喝水，注意休息，避免辛辣刺激食物'
  },
  {
    id: 2,
    date: '2023-03-10',
    department: '外科',
    doctor: '王医生',
    diagnosis: '腕部扭伤',
    recordNo: 'MR20230310002',
    complaint: '右腕疼痛1天',
    prescription: '云南白药喷雾剂 每日3-4次\n布洛芬缓释胶囊 0.3g 每日2次',
    advice: '局部冷敷，避免剧烈活动，一周后复诊'
  }
])

// 预约记录
const appointments = reactive([
  {
    id: 1,
    date: '2023-05-20',
    time: '09:00-09:30',
    department: '内科',
    doctor: '李医生',
    status: '未开始'
  },
  {
    id: 2,
    date: '2023-04-15',
    time: '14:30-15:00',
    department: '内科',
    doctor: '李医生',
    status: '已完成'
  },
  {
    id: 3,
    date: '2023-03-10',
    time: '10:00-10:30',
    department: '外科',
    doctor: '王医生',
    status: '已完成'
  }
])

// 家庭成员
const familyMembers = reactive([
  {
    id: 1,
    name: '张大',
    relation: 'father',
    gender: 'male',
    birthday: '1965-05-10',
    idCard: '110101196505101234'
  },
  {
    id: 2,
    name: '李小',
    relation: 'mother',
    gender: 'female',
    birthday: '1968-08-15',
    idCard: '110101196808151234'
  }
])

// 家庭成员表单
const familyMemberForm = reactive({
  id: '',
  name: '',
  relation: '',
  gender: 'male',
  birthday: '',
  idCard: ''
})

// 密码表单
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 隐私设置
const privacySettings = reactive({
  allowSms: true,
  allowEmail: true,
  shareMedicalRecords: false
})

// 筛选预约记录
const filteredAppointments = computed(() => {
  if (appointmentType.value === 'all') {
    return appointments
  } else if (appointmentType.value === 'upcoming') {
    return appointments.filter(a => a.status === '未开始')
  } else {
    return appointments.filter(a => a.status === '已完成')
  }
})

// 处理菜单选择
const handleMenuSelect = (index) => {
  activeMenu.value = index
}

// 编辑个人资料
const editProfile = () => {
  isEditing.value = true
}

// 保存个人资料
const saveProfile = () => {
  ElMessage.success('个人资料保存成功')
  isEditing.value = false
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
}

// 查看就医记录详情
const viewMedicalRecord = (record) => {
  selectedMedicalRecord.value = record
  medicalRecordDialogVisible.value = true
}

// 打印就医记录
const printMedicalRecord = () => {
  ElMessage.success('正在打印就医记录')
  // 这里可以添加打印逻辑
}

// 下载就医记录
const downloadMedicalRecord = () => {
  ElMessage.success('就医记录已下载')
  // 这里可以添加下载逻辑
}

// 取消预约
const cancelAppointment = (appointment) => {
  ElMessageBox.confirm('确定要取消这个预约吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    appointment.status = '已取消'
    ElMessage.success('预约已取消')
  }).catch(() => {})
}

// 评价预约
const evaluateAppointment = (appointment) => {
  ElMessage.success('感谢您的评价')
  // 这里可以添加评价逻辑
}

// 前往预约页面
const goToAppointment = () => {
  router.push('/user/appointment')
}

// 添加家庭成员
const addFamilyMember = () => {
  familyMemberDialogType.value = 'add'
  Object.keys(familyMemberForm).forEach(key => {
    familyMemberForm[key] = key === 'gender' ? 'male' : ''
  })
  familyMemberDialogVisible.value = true
}

// 编辑家庭成员
const editFamilyMember = (member) => {
  familyMemberDialogType.value = 'edit'
  Object.keys(familyMemberForm).forEach(key => {
    familyMemberForm[key] = member[key]
  })
  familyMemberDialogVisible.value = true
}

// 保存家庭成员
const saveFamilyMember = () => {
  if (familyMemberDialogType.value === 'add') {
    familyMembers.push({
      id: Date.now(),
      ...familyMemberForm
    })
    ElMessage.success('家庭成员添加成功')
  } else {
    const index = familyMembers.findIndex(m => m.id === familyMemberForm.id)
    if (index !== -1) {
      Object.assign(familyMembers[index], familyMemberForm)
      ElMessage.success('家庭成员信息更新成功')
    }
  }
  familyMemberDialogVisible.value = false
}

// 删除家庭成员
const deleteFamilyMember = (member) => {
  ElMessageBox.confirm('确定要删除这个家庭成员吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const index = familyMembers.findIndex(m => m.id === member.id)
    if (index !== -1) {
      familyMembers.splice(index, 1)
      ElMessage.success('家庭成员已删除')
    }
  }).catch(() => {})
}

// 修改密码
const changePassword = () => {
  if (passwordForm.newPassword !== passwordForm.confirmPassword) {
    ElMessage.error('两次输入的密码不一致')
    return
  }
  
  ElMessage.success('密码修改成功')
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// 保存隐私设置
const savePrivacySettings = () => {
  ElMessage.success('隐私设置已保存')
}
</script>

<style scoped>
.user-center {
  padding: 20px;
}

.user-info-card, .content-card {
  margin-bottom: 20px;
}

.user-avatar {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin-bottom: 20px;
}

.upload-avatar {
  margin-top: 10px;
}

.user-basic-info {
  text-align: center;
}

.user-id {
  color: #909399;
  font-size: 14px;
  margin-top: 5px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.record-detail {
  padding: 20px;
}

.record-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 20px;
}
</style> 